package org.jeecg.modules.cosmetic.handler;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.cosmetic.entity.*;
import org.jeecg.modules.cosmetic.model.dto.*;
import org.jeecg.modules.cosmetic.model.vo.*;
import org.jeecg.modules.cosmetic.service.*;
import org.jeecg.modules.cosmetic.utils.CurrentUserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ToxicologicalHandler {

    @Resource
    private ITToxicologicalService toxicologicalService;

    @Resource
    private ITToxicologicalFieldService toxicologicalFieldService;

    @Resource
    private ITToxicologicalWhitenService toxicologicalWhitenService;

    @Resource
    private ITToxicologicalEdibleService toxicologicalEdibleService;

    @Resource
    private ITToxicologicalSublistService toxicologicalSublistService;

    @Resource
    private ITToxicologicalCsaService toxicologicalCsaService;

    @Resource
    private ITSccsProductService sccsProductService;

    @Resource
    private ITToxicologicalReportService toxicologicalReportService;

    @Resource
    private ITToxicologicalIecicService toxicologicalIecicService;

    @Resource
    private ITToxicologicalFileService toxicologicalFileService;

    @Value("${jeecg.path.upload}")
    private String uploadPath;

    @Value("${jeecg.uploadType}")
    private String uploadType;

    /**
     * 分页
     * @param pageVO
     * @return
     */
    public Result<IPage<ToxPageDTO>> getPage(ToxPageVO pageVO) {
        // 封装页数和大小
        if (ObjectUtils.isEmpty(pageVO.getPageNo())) pageVO.setPageNo(1);
        if (ObjectUtils.isEmpty(pageVO.getPageSize())) pageVO.setPageSize(10);
        Page<TToxicological> page = new Page<>(pageVO.getPageNo(), pageVO.getPageSize());

        // 查询数据
        List<ToxPageDTO> pageDTOs = Lists.newArrayList();
        Page<TToxicological> pageList = toxicologicalService.getPage(page, pageVO.getParams(), pageVO.getType());
        if(CollectionUtils.isNotEmpty(pageList.getRecords())) {
            pageList.getRecords().stream().map(m -> {
                List<ToxFieldDTO> fieldList = toxicologicalFieldService.getListByToxId(m.getId());
                ToxPageDTO dto = new ToxPageDTO();
                BeanUtils.copyProperties(m, dto);
                dto.setOtherNameList(fieldList);
                return dto;
            }).collect(Collectors.toCollection(() -> pageDTOs));
        }

        // 封装返回数据
        IPage<ToxPageDTO> iPage = new Page<>();
        BeanUtils.copyProperties(page, iPage);
        iPage.setRecords(pageDTOs);
        return Result.ok(iPage);
    }

    /**
     * 保存原料
     * @param vo
     * @return
     */
    public Result<?> saveRaw(ToxRawVO vo ) {
        // 封装数据
        TToxicological tToxicological = new TToxicological();
        switch (vo.getType()) {
            case 1: tToxicological.setInciName(vo.getName()); tToxicological.setInciPick(0); break;
            case 2: tToxicological.setCnName(vo.getName()); tToxicological.setCnPick(0); break;
            case 3: tToxicological.setRnName(vo.getName()); tToxicological.setRnPick(0); break;
            case 4: tToxicological.setInpacName(vo.getName()); tToxicological.setInpacPick(0); break;
        }

        // 处理编码
        String toxNumber = toxicologicalService.getNumber();
        int i = 0;
        if (StringUtils.isNotBlank(toxNumber)) {
            i = Integer.parseInt(toxNumber.substring(toxNumber.length() - 6));
        }
        String number = "SBS" + "-" + String.format("%06d", i+1);
        tToxicological.setNumber(number);
        tToxicological.setCreateBy(CurrentUserUtil.authInfo().getName());
        tToxicological.setUpdateBy(CurrentUserUtil.authInfo().getName());

        // 保存数据
        toxicologicalService.save(tToxicological);
        return Result.ok(tToxicological.getId());
    }

    /**
     * 查询主表模块数据
     * @param id
     * @return
     */
    public ToxModuleDTO getTox(Long id) {
        // 查询主表数据
        TToxicological toxicological = toxicologicalService.getOne(new LambdaQueryWrapper<TToxicological>().eq(TToxicological::getId, id));
        Optional.ofNullable(toxicological).orElseThrow(() -> new JeecgBootException("毒理信息不存在"));

        // 查询其它字段数据
        List<ToxFieldDTO> fieldList = toxicologicalFieldService.getListByToxId(id);

        // 查询美白列表数据
        List<ToxWhitenDTO> whitenList = toxicologicalWhitenService.getListByToxId(id);

        // 查询IECIC数据
        List<ToxIecicDTO> iecicList = toxicologicalIecicService.getListByToxId(id);

        // 查询资料数据
        List<ToxFileDTO> fileList = toxicologicalFileService.getToxFile(id);

        // 返回封装数据
        ToxModuleDTO dto = new ToxModuleDTO();
        BeanUtils.copyProperties(toxicological, dto);
        dto.setOtherNameList(fieldList);
        dto.setWhitenList(whitenList);
        dto.setIecicList(iecicList);
        dto.setFileList(fileList);
        return dto;
    }

    /**
     * 更新标识信息-可用浓度-KCII信息
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @DS("cosmetic-datasource")
    public Result<?> updateTox(ToxModuleVO vo) {
        // 先处理主表数据
        TToxicological tToxicological = new TToxicological();
        BeanUtils.copyProperties(vo, tToxicological);
        tToxicological.setUpdateBy(CurrentUserUtil.authInfo().getName());
        toxicologicalService.updateById(tToxicological);

        // 处理其它字段信息
        if (CollectionUtils.isNotEmpty(vo.getOtherNameList())) {
            toxicologicalFieldService.removeBatchByIds(toxicologicalFieldService.list(new LambdaQueryWrapper<TToxicologicalField>().eq(TToxicologicalField::getToxId, vo.getId())));
            vo.getOtherNameList().forEach(m -> {
                TToxicologicalField tToxicologicalField = new TToxicologicalField();
                BeanUtils.copyProperties(m, tToxicologicalField);
                toxicologicalFieldService.save(tToxicologicalField);
            });
        }

        // 处理美白清单数据
        if (CollectionUtils.isNotEmpty(vo.getWhitenList())) {
            toxicologicalWhitenService.removeBatchByIds(toxicologicalWhitenService.list(new LambdaQueryWrapper<TToxicologicalWhiten>().eq(TToxicologicalWhiten::getToxId, vo.getId())));
            vo.getWhitenList().forEach(m -> {
                TToxicologicalWhiten tToxicologicalWhiten = new TToxicologicalWhiten();
                BeanUtils.copyProperties(m, tToxicologicalWhiten);
                tToxicologicalWhiten.setUpdateBy(CurrentUserUtil.authInfo().getName());
                tToxicologicalWhiten.setCreateBy(CurrentUserUtil.authInfo().getName());
                toxicologicalWhitenService.save(tToxicologicalWhiten);
            });
        }

        // 资料文件
        if (CollectionUtils.isNotEmpty(vo.getFileList())) {
            toxicologicalFileService.removeBatchByIds(toxicologicalFileService.list(new LambdaQueryWrapper<TToxicologicalFile>().eq(TToxicologicalFile::getToxId, vo.getId())));
            vo.getFileList().forEach(m -> {
                TToxicologicalFile tToxicologicalFile = new TToxicologicalFile();
                BeanUtils.copyProperties(m, tToxicologicalFile);
                tToxicologicalFile.setToxId(vo.getId());
                toxicologicalFileService.save(tToxicologicalFile);
            });
        }
        return Result.ok();
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @DS("cosmetic-datasource")
    public boolean delete(Long id) {
        // 删除可食用性数据
        toxicologicalEdibleService.removeBatchByIds(toxicologicalEdibleService.list(new LambdaQueryWrapper<TToxicologicalEdible>().eq(TToxicologicalEdible::getToxId, id)));

        // 删除透皮-系统毒性模块
        toxicologicalSublistService.removeBatchByIds(toxicologicalSublistService.list(new LambdaQueryWrapper<TToxicologicalSublist>().eq(TToxicologicalSublist::getToxId, id)));

        // 删除CSA模块和产品信息数据
        List<TToxicologicalCsa> csaList = toxicologicalCsaService.list(new LambdaQueryWrapper<TToxicologicalCsa>().eq(TToxicologicalCsa::getToxId, id));
        csaList.forEach(m -> {
            if (m.getForm() == 2) {
                sccsProductService.removeBatchByIds(sccsProductService.list(new LambdaQueryWrapper<TSccsProduct>().eq(TSccsProduct::getCsaId, m.getId())));
            }
        });
        toxicologicalCsaService.removeBatchByIds(csaList);

        // 删除美白清单数据
        toxicologicalWhitenService.removeBatchByIds(toxicologicalWhitenService.list(new LambdaQueryWrapper<TToxicologicalWhiten>().eq(TToxicologicalWhiten::getToxId, id)));

        // 删除其它字段数据
        toxicologicalFieldService.removeBatchByIds(toxicologicalFieldService.list(new LambdaQueryWrapper<TToxicologicalField>().eq(TToxicologicalField::getToxId, id)));

        // 删除报告信息
        toxicologicalReportService.removeBatchByIds(toxicologicalReportService.list(new LambdaQueryWrapper<TToxicologicalReport>().eq(TToxicologicalReport::getToxId, id)));

        // 删除IECIC数据
        toxicologicalIecicService.removeBatchByIds(toxicologicalIecicService.list(new LambdaQueryWrapper<TToxicologicalIecic>().eq(TToxicologicalIecic::getToxId, id)));

        // 删除资料数据
        toxicologicalFileService.removeBatchByIds(toxicologicalFileService.list(new LambdaQueryWrapper<TToxicologicalFile>().eq(TToxicologicalFile::getToxId, id)));

        // 删除主表数据
        return toxicologicalService.removeById(id);
    }

    /**
     * 更新IECIC备注信息
     * @param vo
     * @return
     */
    public Result<?> updateRemark(IecicRemarkVO vo) {
        // 先处理主表数据
        TToxicological toxicological = toxicologicalService.getById(vo.getId());
        if (vo.getRemark() != null) toxicological.setRemark(vo.getRemark());
        toxicological.setUpdateBy(CurrentUserUtil.authInfo().getName());
        return Result.ok(toxicologicalService.updateById(toxicological));
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    public Result<?> upload(MultipartFile file) {
        ToxFileDTO dto = new ToxFileDTO();
        try {
            dto.setName(file.getOriginalFilename());
            dto.setUrl(CommonUtils.upload(file, uploadPath, uploadType));
            return Result.ok(dto);
        } catch (Exception e) {
            return Result.error("图片上传异常");
        }
    }
}
